<template>
  <div>
    <a-modal :title="title" :visible="modalVisible" :confirm-loading="confirmLoading" @ok="handleOk"
      @cancel="handleCancel">
      <a-form-model :model="roleForm" ref="roleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules">
        <a-form-model-item label="身份名称" prop="name">
          <a-input v-model.trim="roleForm.name" :maxLength="20" placeholder="请输入身份名称" />
        </a-form-model-item>
        <a-form-model-item label="备注信息" prop="remark" class="form-item">
          <a-input v-model.trim="roleForm.remark" :maxLength="20" placeholder="请输入备注信息" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { addRoleInfo, saveRoleInfo } from "@/services/roleManage";
import Regex from "@/utils/regex.js";
export default {
  name: "role-modal",
  data() {
    const nameCheckFun = (rule, value, callback) => {
      if (!value) {
        callback(new Error("名称不能为空"));
      } else if (!Regex.userName.test(value)) {
        callback(new Error("请输入汉字、字母、数字"));
      } else {
        callback();
      }
    };
    return {
      modalVisible: false,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      title: "新增组织身份",
      type: 'add',
      roleForm: {
        id: undefined,
        name: "",
        remark: ""
      },
      rules: {
        name: [{ required: true, validator: nameCheckFun, trigger: "blur" }]
      }
    };
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  methods: {
    show(data, type) {
      this.type = type;
      if (type === 'edit') {
        this.title = "编辑组织身份"
      }
      this.modalVisible = true;
      this.roleForm = { ...data }
    },
    handleOk() {
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          let params = {
            ...this.roleForm,
            departmentId: this.id
          };
          let roleApi = this.type === "edit" ? saveRoleInfo : addRoleInfo;
          const {
            data: { code, message }
          } = await roleApi(params);
          if (code === 200) {
            this.$refs.roleForm.resetFields();
            let message = this.type === "edit" ? "编辑成功" : "新增成功";
            this.$message.success(message);
            this.$emit("success")
            this.modalVisible = false;
          } else {
            this.$message.warning(message);
          }
        } else {
          return false;
        }
      });
    },
    handleCancel() {
      this.modalVisible = false;
      this.$refs.roleForm.clearValidate();
    }
  }
};
</script>

<style lang="less" scoped>
</style>
